<script lang="ts">
import { ref, defineComponent } from "vue";
import {
  Calendar,
  CalendarOptions,
  EventApi,
  DateSelectArg,
  EventClickArg,
} from "@fullcalendar/core";
import FullCalendar from "@fullcalendar/vue3";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import listPlugin from "@fullcalendar/list";
import interactionPlugin from "@fullcalendar/interaction";
import { INITIAL_EVENTS, createEventId } from "../utils/event";
import axios from "../utils/request";

interface TableItem {
  [key: string]: string;
}

export default defineComponent({
  components: {
    FullCalendar,
  },
  data() {
    return {
      preEvents: [] as EventApi[],
      calendarOptions: {
        plugins: [
          dayGridPlugin,
          timeGridPlugin,
          interactionPlugin, // needed for dateClick
          listPlugin,
        ],
        initialView: "dayGridMonth",
        initialEvents: INITIAL_EVENTS, // alternatively, use the `events` setting to fetch from a feed
        headerToolbar: {
          left: "prevYear,prev,next,nextYear today",
          center: "title",
          right: "dayGridMonth,timeGridWeek,listDay",
        },
        buttonText: {
          month: "月",
          week: "周",
          day: "天",
        },
        // views:{
        //   dayGridPlugin:{
        //     titleFormat:{ year: 'numeric', month: '2-digit', day: '2-digit' },

        //   }
        // },
        locale: "zh-cn", // 设置语言
        height: "auto", //高度自动

        navLinks: true, //定义单元格是否可点击
        editable: true,
        selectable: true,
        selectMirror: true,
        dayMaxEvents: true,
        weekends: true,
        weekNumbers: true, //显示当前是第几周
        droppable: true, //是否允许接收外部事件
        select: this.handleDateSelect,
        eventClick: this.handleEventClick,
        eventsSet: this.handleEvents,
        /* you can update a remote database when these fire:
        eventAdd:
        eventChange:
        eventRemove:
        */
        lazyFetching: true, // 懒加载
      } as CalendarOptions,
      currentEvents: [] as EventApi[],
      calendarApi: ref<Calendar>(),
    };
  },
  mounted() {
    this.calendarApi = (this.$refs.FullCalendar as any).getApi();

    this.calendarApi?.addEvent({
      id: createEventId(),
      title: "第一次事件",
      start: "2024-01-13T12:00:00",
    });

    this.calendarApi?.removeAllEvents();

    axios.get("/conference_situation/api/conference_id", { params: { person_id: localStorage.getItem('person_id') } })
      .then(res => res.data.results)
      .then(conference_situation => {
        // 获取会议情况后，再发起请求获取会议信息
        conference_situation.forEach((situation: TableItem) => {
          //console.log('-----------------------', situation)
          axios.get("/conference/api/title,preset_time", { params: { id: situation.conference_id } })
            .then(res => res.data.results)
            .then(conference => {
              console.log('-----------------------', conference)
              // 将获取的会议信息添加到日历中
              // conference.forEach((conf: TableItem) => {
              for (let conf of conference) {
                this.calendarApi?.addEvent({
                  id: createEventId(),
                  title: conf.title,
                  start: conf.preset_time
                });
              }
              // });
              console.log("---", this.currentEvents);
            })
            .then(conference => {
              this.preEvents = this.currentEvents.filter(i => new Date(i.startStr) > new Date())
            })
        });
      });
  },
  methods: {
    handleWeekendsToggle() {
      this.calendarOptions.weekends = !this.calendarOptions.weekends; // 更新属性
    },
    handleDateSelect(selectInfo: DateSelectArg) {
      let calendarApi = selectInfo.view.calendar;
      console.log(selectInfo);
      
      if (selectInfo.view.type === "dayGridMonth") {
        calendarApi.changeView("timeGridWeek");
        calendarApi.gotoDate(selectInfo.startStr); 
        return;
      }

      let title = prompt("请输入会议名称：");
      calendarApi.unselect(); // 清除日期片

      if (title) {
        calendarApi.addEvent({
          id: createEventId(),
          title,
          start: selectInfo.startStr,
          end: selectInfo.endStr,
          allDay: selectInfo.allDay,
        });
      }
    },
    handleEventClick(clickInfo: EventClickArg) {
      if (confirm(`确定要删除 '${clickInfo.event.title}吗？'`)) {
        clickInfo.event.remove();
      }
    },
    handleEvents(events: EventApi[]) {
      this.currentEvents = events;
    },
    formatDate(dateTimeString:string) {
      let date = new Date(dateTimeString);
      console.log('-', date)
      // 使用 JavaScript 的日期对象方法来格式化日期
      let formattedDate = date.toLocaleDateString( 'en-CN',{
        month: 'numeric',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
      });
      return formattedDate;
    }
  }
});
</script>

<template>
  <div class="demo-app">
    <div class="demo-app-sidebar">
      <div class="demo-app-sidebar-section">
        <label>
          <input type="checkbox" :checked="calendarOptions.weekends" @change="handleWeekendsToggle" />
          切换周末视图
        </label>
      </div>
      <div class="demo-app-sidebar-section">
        <h2>所有会议({{ preEvents.length }})</h2>
        <ul>
          <li v-for="event in preEvents" :key="event.id">
            <b>{{ formatDate(event.startStr) }}</b>
            <i>{{ event.title }}</i>
          </li>
        </ul>
      </div>
    </div>
    <div class="demo-app-main">
      <FullCalendar ref="FullCalendar" class="demo-app-calendar" :options="calendarOptions">
        <template v-slot:eventContent="arg">
          <b>{{ arg.timeText }}</b>
          <i>{{ arg.event.title }}</i>
        </template>
      </FullCalendar>
    </div>
  </div>
</template>

<style lang="css">
h2 {
  margin: 0;
  font-size: 16px;
}

ul {
  margin: 0;
  padding: 0 0 0 1.5em;
}

li {
  margin: 1.5em 0;
  padding: 0;
}

b {
  /* used for event dates/times */
  margin-right: 3px;
}

.demo-app {
  display: flex;
  min-height: 100%;
  font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
  font-size: 14px;
}

.demo-app-sidebar {
  width: 300px;
  line-height: 1.5;
  background: #eaf9ff;
  border-right: 1px solid #d3e2e8;
}

.demo-app-sidebar-section {
  padding: 2em;
}

.demo-app-main {
  flex-grow: 1;
  padding: 3em;
}

.fc {
  /* the calendar root */
  max-width: 1100px;
  margin: 0 auto;
}
</style>
